﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GRWL.BZSC.UI.BaseDataSvc;
using GRWL.BZSC.UI.CustomCtrl;
using UserCtrl;

namespace GRWL.BZSC.UI
{
    public partial class QuotationFrm : BaseFrm
    {
        //public CodeRuleFrm.CodeRule codeRule { get; set; }
        //public GRWL.BZSC.UI.Common.BillOperateType EditStatus;

        public XQuotation XQuotationMain;
        public XQuoteDetial[] XQuotationDetial;

        private TB_Trader Trader;
        private TB_Department Department;

        private TB_User[] Users;
        private XUser[] XUsers;

        private DataTable tXUsers;

        bool bEdit, bConfirm, bPrint;

        /// <summary>
        /// 临时变量日期控件
        /// </summary>
        DateTimePicker _DTP = new DateTimePicker();
        UDataGridView theView;

        #region 自定义
        public override void EditStatusChanged()
        {
            RefreshStatus();
            //btnAppend.Enabled = (EditStatus != Common.BillOperateType.Add) && (EditStatus != Common.BillOperateType.Update);
            //btnOpen.Enabled = (EditStatus == Common.BillOperateType.None);
            btnSave.Enabled = bEdit;
            //btnSelect.Enabled = (EditStatus == Common.BillOperateType.Add) || (EditStatus == Common.BillOperateType.Update);
            btnDelete.Enabled = bEdit;
            btnAddItem.Enabled = bEdit;
            btnDelItem.Enabled = bEdit;
            btnRapid.Enabled = bEdit;
            btnConfirm.Enabled = bConfirm;
            btnPrint.Enabled = bPrint;
        }

        private void RefreshStatus()
        {
            bEdit = (EditStatus == Common.BillOperateType.Add) || (EditStatus == Common.BillOperateType.Update);
            bConfirm = (tMain.Rows.Count > 0);
            if (bConfirm)
                bConfirm = (Common.StringToInt(tMain.Rows[0]["id"].ToString()) > 0);
            bPrint = (EditStatus != Common.BillOperateType.Add) && (EditStatus != Common.BillOperateType.Update);
        }

        private void SetControlsStatus(bool SetEnabledFlag)
        {

            //txtcode.ReadOnly = !SetEnabledFlag;
            dpDate.Enabled = SetEnabledFlag;
            txtOperator.ReadOnly = !SetEnabledFlag;
            //dpCreateTime.Enabled = SetEnabledFlag;
            Traderselector.Enabled = SetEnabledFlag;
            cbbBusinessMan.Enabled = SetEnabledFlag;
            dpExpire.Enabled = SetEnabledFlag;
            deptSelector.Enabled = SetEnabledFlag;
            txtassessor.ReadOnly = !SetEnabledFlag;
            //dpverifyTime.Enabled = SetEnabledFlag;
            //txtIsVerify.ReadOnly = !SetEnabledFlag;
            //txtCurrency.ReadOnly = !SetEnabledFlag;
            txtTax.Enabled = SetEnabledFlag;
            //txtTaxRate.ReadOnly = !SetEnabledFlag;
            txtStatus.ReadOnly = !SetEnabledFlag;
            txtMemo.ReadOnly = !SetEnabledFlag;

            //theView.SetAddStates(SetEnabledFlag);
            theView.ReadOnly = !SetEnabledFlag;

            //指定表格中只读的字段，防止被用户错误修改
            if (SetEnabledFlag)
            {
                theView.Columns["MaterialName"].ReadOnly = SetEnabledFlag;
                theView.Columns["CategoryName"].ReadOnly = SetEnabledFlag;
                theView.Columns["brand"].ReadOnly = SetEnabledFlag;
                theView.Columns["specs"].ReadOnly = SetEnabledFlag;
                theView.Columns["unit"].ReadOnly = SetEnabledFlag;
                theView.Columns["minnum"].ReadOnly = SetEnabledFlag;
                theView.Columns["maxnum"].ReadOnly = SetEnabledFlag;
                theView.Columns["taxprice"].ReadOnly = SetEnabledFlag;
            }
        }

        private void DataBindAll()
        {
            txtcode.Text = tMain.Rows[0]["code"].ToString();

            if (!string.IsNullOrEmpty(tMain.Rows[0]["quoteDate"].ToString()))
                dpDate.Value = (DateTime)tMain.Rows[0]["quoteDate"];
            if (!string.IsNullOrEmpty(tMain.Rows[0]["expire"].ToString()))
                dpExpire.Value = (DateTime)tMain.Rows[0]["expire"];

            txtStatus.Text = tMain.Rows[0]["status"].ToString();
            txtTaxRate.Text = tMain.Rows[0]["taxrate"].ToString();
            cbbBusinessMan.Text = tMain.Rows[0]["BusinessName"].ToString();

            txtOperator.Text = tMain.Rows[0]["OperatorName"].ToString();
            dpCreateTime.Text = tMain.Rows[0]["createtime"].ToString();
            txtassessor.Text = tMain.Rows[0]["AssessorName"].ToString();
            dpverifyTime.Text = tMain.Rows[0]["verifytime"].ToString();
            txtMemo.Text = tMain.Rows[0]["memo"].ToString();

            if (!string.IsNullOrEmpty(tMain.Rows[0]["trader"].ToString()))
            {
                SetTrader();
            }

            if (!string.IsNullOrEmpty(tMain.Rows[0]["department"].ToString()))
            {
                SetDepartment();
                UpdateBizManList((int)tMain.Rows[0]["department"]);
            }

            // 检查窗体税目中有无该项目，没有就加入
            if (!string.IsNullOrEmpty(tMain.Rows[0]["taxrate"].ToString()))
            {
                string cTax = tMain.Rows[0]["taxrate"].ToString();
                if (Common.StringToDecimal(cTax) > 0)
                {
                    if (txtTax.Items.IndexOf(cTax) < 0)
                        txtTax.Items.Add(cTax);

                    txtTax.SelectedIndex = txtTax.Items.IndexOf(cTax);
                }
                else
                    txtTax.SelectedIndex = 0;
            }
            else
                txtTax.SelectedIndex = 0;

            theView.DataSource = tDetail;
        }

        private void SetTrader()
        {
            SelectItem item = new SelectItem();
            Trader = BaseDataProxy.GetTrader((int)tMain.Rows[0]["trader"]);
            if (Trader != null)
            {
                item.Name = Trader.name;
                item.Key = Trader.code;
                item.Value = Trader.id.ToString();
                Traderselector.SetSelected(item);
            }
        }

        private void SetDepartment()
        {
            SelectItem item = new SelectItem();
            Department = BaseDataProxy.GetDepartment((int)tMain.Rows[0]["department"]);
            if (Department != null)
            {
                item.Name = Department.name;
                item.Key = Department.code;
                item.Value = Department.id.ToString();
                deptSelector.SetSelected(item);
            }
        }

        private void UpdateBizManList(int DepartmentId)
        {
            XUsers = BaseDataProxy.FindUsers(DepartmentId, "", "");

            cbbBusinessMan.Items.Clear();
            foreach (XUser dp in XUsers)
            {
                cbbBusinessMan.Items.Add(dp.User);
            }
            cbbBusinessMan.DisplayMember = "name";
            cbbBusinessMan.ValueMember = "id";
        }

        private void OpenQuotation(int r)
        {
            XQuotationMain = BaseDataProxy.GetXQuotation(r);
            XQuotationDetial = BaseDataProxy.GetXQuoteDetials(r);

            //    //表头内容
            IEnumerable<XQuotation> ary = new List<XQuotation>() { XQuotationMain };
            tMain = ary.ConvertToDataTable<TB_Quotation>();
            //    //表体内容
            tDetail = XQuotationDetial.ConvertToDataTable<TB_QuoteDetail>();

            if ((bool)tMain.Rows[0]["isVerify"] == true)
            {
                //审批后,不允许再修改
                EditStatus = Common.BillOperateType.View;
                SetControlsStatus(false);
            }
            else
            {
                //未审批,允许再修改
                tMain.Rows[0]["mender"] = SysLoginUserInfo.UserId;
                tMain.Rows[0]["MenderName"] = SysLoginUserInfo.UserName;
                tMain.Rows[0]["updateTime"] = DateTime.Today;
                EditStatus = Common.BillOperateType.Update;
                SetControlsStatus(true);
            }

            DataBindAll();
        }

        private void ResetData()
        {
            tMain.Rows.Clear();
            tDetail.Rows.Clear();
            tMain.Rows.Add();
            tMain.AcceptChanges();
            tDetail.AcceptChanges();
            DataBindAll();
        }

        private DataRow NewGridRow()
        {
            //新行默认值设定
            DataRow dr = tDetail.NewRow();
            dr["Discount"] = 1;
            dr["qttnCode"] = tMain.Rows[0]["code"];
            dr["minNum"] = 1;
            dr["maxNum"] = 10000;
            tDetail.Rows.Add(dr);
            return dr;
        }

        #endregion

        #region 窗体部分
        public QuotationFrm()
        {
            InitializeComponent();

            this.BaseDataProxy = new BaseDataClient();
            this.BaseDataProxy.Open();

            this.codeRule = new CodeRuleFrm.CodeRule();
            EditStatus = Common.BillOperateType.None;

            BillPrefix = "BJ";
        }

        private void QuotationFrm_Load(object sender, EventArgs e)
        {
            theView = gvQuotation;
            theView.Controls.Add(this._DTP);  //把时间控件加入DataGridView
            this._DTP.Visible = false;  //先不让它显示
            this._DTP.Format = DateTimePickerFormat.Custom;
            this._DTP.TextChanged += new EventHandler(dtp_TextChange); //为时间控件加入事件dtp_TextChange            

            theView.CellClick += new DataGridViewCellEventHandler(theView_CellClick);
            theView.ColumnWidthChanged += new DataGridViewColumnEventHandler(theView_ColumnWidthChanged);
            theView.Scroll += new ScrollEventHandler(theView_Scroll);

            SetControlsStatus(false);

            theView.CellDoubleClick += new DataGridViewCellEventHandler(theView_CellDoubleClick);
            theView.CellEndEdit += new DataGridViewCellEventHandler(theView_CellEndEdit);
            theView.RowsAdded += new DataGridViewRowsAddedEventHandler(theView_RowsAdded);
            theView.RowsRemoved += new DataGridViewRowsRemovedEventHandler(theView_RowsRemoved);
            theView.CellFormatting += new DataGridViewCellFormattingEventHandler(theView_CellFormatting);

            theView.AutoGenerateColumns = false;
        }

        private void btnAppend_Click(object sender, EventArgs e)
        {
            EditStatus = Common.BillOperateType.Add;
            SetControlsStatus(true);

            tMain.Clear();
            DataRow NewMainRow = tMain.NewRow();
            // 开新单时，单号为空，保存时申请后显示
            NewMainRow["code"] = ""; // BaseDataProxy.GetSerialNo(1, BillPrefix, 4, true, true, true);
            NewMainRow["operator"] = SysLoginUserInfo.UserId;
            NewMainRow["OperatorName"] = SysLoginUserInfo.UserName;
            NewMainRow["createtime"] = DateTime.Today;
            NewMainRow["status"] = "未批";
            NewMainRow["isVerify"] = false;
            NewMainRow["isClosed"] = false;

            tMain.Rows.Add(NewMainRow);
            tMain.AcceptChanges();

            tDetail.Clear();
            NewGridRow();
            tDetail.AcceptChanges();

            DataBindAll();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            //加载打开单据
            FindBillFrm frm = new FindBillFrm();
            frm.AllowMulitSelect = false;
            frm.SelectBillType = GRWL.BZSC.Common.EnumCommon.BillType.BJ;
            frm.ShowDialog();
            if (frm.DialogResult == DialogResult.OK)
            {
                if (frm.SelectedItems != null)
                {
                    QQuotation qqu = OTConverter.ConvertToObject<QQuotation>(frm.SelectedItems);
                    OpenQuotation(qqu.Id);
                }
            }

            //SelectBillFrm frm = new SelectBillFrm();
            //frm.SetCondition(GRWL.BZSC.Common.EnumCommon.BillType.BJ, BillPrefix, false);
            //frm.ShowDialog();
            //if (frm.SelectBills.Count > 0)
            //{
            //    OpenQuotation(frm.SelectBills[0].BillId);
            //}
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
                return;

            if (EditStatus == Common.BillOperateType.Add)
            {
                if (string.IsNullOrEmpty(tMain.Rows[0]["code"].ToString()))
                {
                    tMain.Rows[0]["code"] = BaseDataProxy.GetSerialNo(1, BillPrefix, 4, true, true, true);
                    txtcode.Text = tMain.Rows[0]["code"].ToString();
                }
            }

            tMain.Rows[0]["quoteDate"] = Common.ToDate(dpDate.Value);
            tMain.Rows[0]["expire"] = Common.ToDate(dpExpire.Value);

            if (cbbBusinessMan.SelectedItem == null)
            {
                tMain.Rows[0]["businessman"] = DBNull.Value;
                tMain.Rows[0]["BusinessName"] = "";
            }
            else
            {
                tMain.Rows[0]["businessman"] = ((TB_User)cbbBusinessMan.SelectedItem).id;
                tMain.Rows[0]["BusinessName"] = ((TB_User)cbbBusinessMan.SelectedItem).name;
            }

            if (txtTax.Text.Trim() != "")
                tMain.Rows[0]["tax"] = Common.StringToDecimal(txtTax.Text.Trim());

            if (txtTaxRate.Text.Trim() != "")
                tMain.Rows[0]["taxrate"] = txtTaxRate.Text.Trim();

            tMain.AcceptChanges();

            if (theView.Rows.Count == 0)
            {
                MessageBox.Show("单据明细记录为空不可以保存。");
                return;
            }

            foreach (DataGridViewRow TheRow in theView.Rows)
            {
                if ((string.IsNullOrEmpty(TheRow.Cells["material"].Value.ToString())) || (string.IsNullOrEmpty(TheRow.Cells["materialCode"].Value.ToString())))
                {
                    theView.CurrentCell = TheRow.Cells["materialCode"];
                    MessageBox.Show("输入的物资不正确，请重新输入。");
                    return;
                }
            }

            foreach (DataRow dr in tDetail.Rows)
            {
                if (string.IsNullOrEmpty(dr["qttncode"].ToString()))
                    dr["qttncode"] = tMain.Rows[0]["code"];
            }
            tDetail.AcceptChanges();

            TB_Quotation Quotation = OTConverter.ConvertToObject<TB_Quotation>(tMain.Rows[0]);

            List<TB_QuoteDetail> LQuoDetails = OTConverter.ConvertTableToObject<TB_QuoteDetail>(theView.DataSource as DataTable);

            TB_QuoteDetail[] QuoDetails = LQuoDetails.ToArray();

            int iAddID = -1;
            bool bUpdate = false;

            if (EditStatus == Common.BillOperateType.Add)
            {
                tMain.AcceptChanges();
                Quotation.TB_QuoteDetail = QuoDetails;
                iAddID = BaseDataProxy.AddQuotation(Quotation);
                tMain.Rows[0]["id"] = iAddID;
                tMain.AcceptChanges();
            }
            else // (EditStatus == Common.BillOperateType.Update)
            {
                Quotation.TB_QuoteDetail = QuoDetails;
                bUpdate = BaseDataProxy.UpdateQuotation(Quotation, true);
            }

            if (((EditStatus == Common.BillOperateType.Add) && (iAddID > 0)) || ((EditStatus == Common.BillOperateType.Update) && (bUpdate)))
            {
                MessageBox.Show("已成功保存单据.");
                EditStatus = Common.BillOperateType.Update;
                OpenQuotation((int)tMain.Rows[0]["id"]);
            }
            else
                MessageBox.Show("保存单据失败.");
        }


        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (theView.CurrentCell == null || theView.CurrentCell.RowIndex < 0) return;

            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
                return;

            if ((bool)tMain.Rows[0]["isVerify"] == true)
            {
                MessageBox.Show("无法删除已审批单据.");
                return;
            }

            int BillId = Common.StringToInt(tMain.Rows[0]["ID"].ToString());
            string message = "是否删除单据？";
            string caption = "确认";
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            DialogResult result = MessageBox.Show(message, caption, buttons);
            if (result == DialogResult.Yes)
            {
                if (BillId == 0)
                {
                    ResetData();
                    MessageBox.Show("已成功删除单据");
                    return;
                }

                if (BaseDataProxy.DeleteQuotation(BillId))
                {
                    MessageBox.Show("已成功删除单据");

                    //重新初始化
                    ResetData();
                    EditStatus = Common.BillOperateType.None;
                }
                else
                    MessageBox.Show("无法删除单据.");
            }
        }

        private void btnAddItem_Click(object sender, EventArgs e)
        {
            NewGridRow();
        }

        private void btnDelItem_Click(object sender, EventArgs e)
        {
            if (theView.RowCount >= 0)
            {
                theView.Rows.RemoveAt(theView.CurrentRow.Index);
                tDetail.AcceptChanges();
                //EditStatus = Common.BillOperateType.Delete;
                if (theView.RowCount == 0)
                {
                    NewGridRow();
                    tDetail.AcceptChanges();
                }
            }
        }

        private void btnRapid_Click(object sender, EventArgs e)
        {
            GetMaterial();
        }

        private void GetMaterial()
        {
            FindMaterialFrm frm = new FindMaterialFrm();
            frm.Text = "选择物资";
            if (frm.ShowDialog() == DialogResult.OK)
            {
                DataGridViewRow dr = theView.CurrentRow;
                dr.Cells["material"].Value = frm.SelectorItem.Id;
                dr.Cells["materialCode"].Value = frm.SelectorItem.Code;
                dr.Cells["unit"].Value = frm.SelectorItem.Unit;
                dr.Cells["brand"].Value = frm.SelectorItem.Brand;
                dr.Cells["specs"].Value = frm.SelectorItem.Specs;
                dr.Cells["MaterialName"].Value = frm.SelectorItem.CnName;
                TB_Material tMaterial = BaseDataProxy.GetMaterial((int)frm.SelectorItem.Id);
                TB_Options tOption = BaseDataProxy.GetOption((int)tMaterial.category);
                dr.Cells["CategoryName"].Value = tOption.name;
                //theView.CurrentRow.Cells["traderMtrlModel"].Value = frm.SelectorItem.Specs;
                return;
            }
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            //审批

        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            //打印
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            EditStatus = Common.BillOperateType.None;

            this.Close();
        }

        private void theView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0)
                return;

            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
            {
                return;
            }
            //物资编号  
            if ((theView.Columns[e.ColumnIndex].Name == "materialcode") | (theView.Columns[e.ColumnIndex].Name == "MaterialName"))
            {
                GetMaterial();
            }
        }

        void theView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
            {
                return;
            }

            //数量、单价等字段编辑后,刷新有关金额计算
            if ((theView.Columns[e.ColumnIndex].Name == "price") || (theView.Columns[e.ColumnIndex].Name == "taxrate") ||
            (theView.Columns[e.ColumnIndex].Name == "taxprice"))
            {
                ReCalcRowMoney(theView.CurrentRow);
            }
        }

        void theView_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo((UDataGridView)sender);
        }

        void theView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo((UDataGridView)sender);
        }

        void theView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            Common.CellFormatColor(sender, e, EditStatus);
        }

        private void theView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            UDataGridView theView = (UDataGridView)sender;
            // 判断所在是否日期选择的列
            if (theView.Columns[e.ColumnIndex].ValueType == typeof(DateTime))
            {
                Rectangle _Rectangle = theView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); //得到所在单元格位置和大小
                this._DTP.Size = new Size(_Rectangle.Width, _Rectangle.Height); //把单元格大小赋给时间控件
                this._DTP.Location = new Point(_Rectangle.X, _Rectangle.Y); //把单元格位置赋给时间控件
                if (theView.CurrentCell.Style.BackColor != Color.Empty)
                    _DTP.CalendarForeColor = theView.CurrentCell.Style.BackColor;
                if ((!theView.CurrentCell.ReadOnly) && (!string.IsNullOrEmpty(theView.CurrentCell.Value.ToString())))
                    this._DTP.Value = (DateTime)theView.CurrentCell.Value;
                this._DTP.Visible = true;  //可以显示控件了
            }
            else
            {
                this._DTP.Visible = false;
            }
        }

        private void theView_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            this._DTP.Visible = false;
        }

        private void theView_Scroll(object sender, ScrollEventArgs e)
        {
            this._DTP.Visible = false;
        }

        private void dtp_TextChange(object sender, EventArgs e)
        {
            theView.CurrentCell.Value = this._DTP.Text.ToString();  //时间控件选择时间时，就把时间赋给所在的单元格
        }

        private void traderSelector_SelectorTextUpdate(object sender, EventArgs e)
        {
            TB_Trader[] datas = BaseDataProxy.FindTraders(null, true, null, null, null, (sender as Selector).GetComboBoxText());
            (sender as Selector).ReBindComboBox<TB_Trader>(datas, "id", "name", "code");
        }

        /// <summary>
        /// 刷新指定行中的金额计算
        /// </summary>
        /// <param name="rCalc"></param>
        /// <returns></returns> 
        private bool ReCalcRowMoney(DataGridViewRow rCalc)
        {
            rCalc.Cells["taxprice"].Value = DBNull.Value;

            decimal dPrice, dTaxRate, dTaxPrice;

            if (theView.CurrentRow.Cells["price"].Value == null)
                return false;
            dPrice = Common.StringToDecimal(rCalc.Cells["price"].Value.ToString());

            if (theView.CurrentRow.Cells["taxrate"].Value == null)
                dTaxRate = 0;
            else
                dTaxRate = Common.StringToDecimal(rCalc.Cells["taxrate"].Value.ToString());

            dTaxPrice = dPrice * (1 + dTaxRate);
            rCalc.Cells["taxprice"].Value = dTaxPrice;

            return true;
        }

        private void Traderselector_SelectorClick(object sender, EventArgs e)
        {
            TraderFrm frm = new TraderFrm();
            frm.Text = "选择往来单位";
            frm.SearchSupplierMode(); // .SetTraderAsSupplier();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                Traderselector.SetSelected(frm.SelectorItem);
                tMain.Rows[0]["trader"] = Common.StringToInt(frm.SelectorItem.Value);
            }
        }

        private void deptSelector_SelectorClick(object sender, EventArgs e)
        {
            DeptFrm frm = new DeptFrm();
            frm.Text = "选择部门";
            if (frm.ShowDialog() == DialogResult.OK)
            {
                deptSelector.SetSelected(frm.SelectorItem);
                tMain.Rows[0]["department"] = Common.StringToInt(frm.SelectorItem.Value);
                UpdateBizManList(int.Parse(frm.SelectorItem.Key.ToString()));
            }
        }

        private void cbbBusinessMan_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sBizManName = cbbBusinessMan.Text;
            IEnumerable<XUser> rDp = from dp in XUsers
                                     where dp.User.name == sBizManName
                                     select dp;

            tMain.Rows[0]["businessman"] = rDp.First().User.id;
        }

        private void btnConfirm_ButtonClick(object sender, EventArgs e)
        {
            btnConfirm.ShowDropDown();
        }

        private void UpdateStatus(int BillId)
        {
            XQuotation XQuotationMain = BaseDataProxy.GetXQuotation(BillId);
            if (XQuotationMain.Quotation.assessor == null)
                tMain.Rows[0]["assessor"] = DBNull.Value;
            else
                tMain.Rows[0]["assessor"] = XQuotationMain.Quotation.assessor;
            if (XQuotationMain.Quotation.verifyTime == null)
                tMain.Rows[0]["verifyTime"] = DBNull.Value;
            else
                tMain.Rows[0]["verifyTime"] = XQuotationMain.Quotation.verifyTime.Value.ToLongTimeString();
            tMain.Rows[0]["status"] = XQuotationMain.Quotation.status;
            tMain.Rows[0]["AssessorName"] = XQuotationMain.AssessorName;
            tMain.AcceptChanges();

            txtassessor.Text = XQuotationMain.AssessorName;
            dpverifyTime.Text = XQuotationMain.Quotation.verifyTime.ToString();
            txtStatus.Text = XQuotationMain.Quotation.status;

        }
        private void btnConfirmOk_Click(object sender, EventArgs e)
        {
            try
            {
                int BillId = Common.StringToInt(tMain.Rows[0]["id"].ToString());
                VerifyBillResult vbResult = BaseDataProxy.VerifyBill(BillPrefix, BillId, SysLoginUserInfo.UserId, true);
                MessageBox.Show(vbResult.Message);
                if (vbResult.Pass)
                {
                    OpenQuotation(BillId);
                    //UpdateStatus(BillId);
                    //EditStatus = Common.BillOperateType.View;
                    //SetControlsStatus(false);
                    //theView.Refresh();
                }
            }
            catch
            {
            }
        }

        private void btnConfirmCancel_Click(object sender, EventArgs e)
        {
            try
            {
                int BillId = Common.StringToInt(tMain.Rows[0]["id"].ToString());
                VerifyBillResult vbResult = BaseDataProxy.VerifyBill(BillPrefix, BillId, SysLoginUserInfo.UserId, false);
                MessageBox.Show(vbResult.Message);
                if (vbResult.Pass)
                {
                    OpenQuotation(BillId);
                    //UpdateStatus(BillId);
                    //EditStatus = Common.BillOperateType.Update;
                    //SetControlsStatus(true);
                    //theView.Refresh();
                }
            }
            catch
            {
            }
        }

        private void txtTax_SelectedIndexChanged(object sender, EventArgs e)
        {
            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
                return;

            decimal dTaxRate;
            if (txtTax.SelectedIndex == 0)
                dTaxRate = 0;
            else
                dTaxRate = Common.StringToDecimal(txtTax.Text);
            tMain.Rows[0]["tax"] = dTaxRate;
            tMain.Rows[0]["taxrate"] = dTaxRate;
            txtTaxRate.Text = dTaxRate.ToString();

            foreach (DataGridViewRow dgvr in theView.Rows)
            {
                if (dTaxRate != 0)
                    dgvr.Cells["taxrate"].Value = dTaxRate;
                else
                    dgvr.Cells["taxrate"].Value = DBNull.Value;
                ReCalcRowMoney(dgvr);
            }

        }

        private void txtTax_Validated(object sender, EventArgs e)
        {
            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
                return;

            decimal dTaxRate = Common.StringToDecimal(txtTax.Text);
            tMain.Rows[0]["tax"] = dTaxRate;
            tMain.Rows[0]["taxrate"] = dTaxRate;
            txtTaxRate.Text = dTaxRate.ToString();

            if (dTaxRate > 0)
                if (txtTax.Items.IndexOf(txtTax.Text) < 0)
                {
                    txtTax.Items.Add(txtTax.Text);

                    foreach (DataGridViewRow dgvr in theView.Rows)
                    {
                        dgvr.Cells["taxrate"].Value = dTaxRate;
                        ReCalcRowMoney(dgvr);
                    }
                }

        }
        #endregion

    }
}
